package com.rc.saas.tenant.controller.tenant;

import com.rc.saas.tenant.common.vo.TResponse;
import com.rc.saas.tenant.model.tenant.TenantSetting;
import com.rc.saas.tenant.model.tenant.TenantUser;
import com.rc.saas.tenant.service.tenant.TenantSettingService;
import com.rc.saas.tenant.shiro.ShiroUtils;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import java.math.BigDecimal;

import static java.math.BigDecimal.ROUND_HALF_UP;


/**
 * @author frog
 * @date 2021/11/13
 */
@Controller
@RequestMapping("/tenantSetting")
public class TenantSettingController {

    private static Logger logger = LogManager.getLogger(TenantSettingController.class);

    @Autowired
    private TenantSettingService tenantSettingService;

    /**
     * 跳转用户充电平台移动终端系统页面
     *
     * @return
     */
    @RequestMapping(value = "/index", method = RequestMethod.GET)
    public String tenantSettingPage(Model model) {
        TenantUser tenantUser = ShiroUtils.getSessionUser();
        TenantSetting tenantSetting = tenantSettingService.selectByPrimaryKey(tenantUser.getTenantCode());
        if (tenantSetting.getMemberRechargeAmountMin() != 0) {
            BigDecimal minAmount = new BigDecimal(tenantSetting.getMemberRechargeAmountMin()).divide(new BigDecimal(100), 2, ROUND_HALF_UP);
            model.addAttribute("minAmount", minAmount);
        }
        model.addAttribute("tenantSetting", tenantSetting);
        return "/templates/tenant/user/tenantSetting";
    }


    /**
     * 保存用户充电平台移动终端系统数据
     *
     * @return
     */
    @RequestMapping(value = "/saveOrUpdateTenantSetting", method = RequestMethod.POST)
    @ResponseBody
    public TResponse saveOrUpdateTenantSetting(TenantSetting tenantSetting, BigDecimal minStartMoney) {
        try {
            tenantSetting.setMemberRechargeAmountMin((minStartMoney.multiply(new BigDecimal(100))).intValue());
            tenantSettingService.updateByPrimaryKeySelective(tenantSetting);
            return TResponse.SUCCESS();
        } catch (Exception e) {
            logger.error("保存用户充电平台移动终端系统数据失败", e);
            return TResponse.FAIL("操作失败");
        }
    }
}
